package org.dce.screencapturer.actions.ui;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;

import org.dce.screencapturer.UI;
import org.dce.screencapturer.actions.ScreenCapturerAction;
import org.dce.screencapturer.util.IconFactory;

@SuppressWarnings("serial")
public class CaptureAreaAction 
	extends ScreenCapturerAction 
	implements AreaSelectorListener{

	private AreaSelector areaSelector;
	public CaptureAreaAction() {
		super("categories.file", "actions.captureArea",IconFactory.getIcon("/images/capture-area.png"));
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		UI ui = getUI();
		
		try {
			Robot robot = new Robot();

			if (ui.isVisible()){
				ui.hideUI();
				Thread.sleep(1000);
			}
			
			Rectangle rect = new Rectangle();
			
			rect.setLocation(0,0);
			rect.setSize(Toolkit.getDefaultToolkit().getScreenSize());
			
			areaSelector = new AreaSelector(robot.createScreenCapture(rect));
			areaSelector.addListener(this);
			areaSelector.setVisible(true);
		}catch (Exception ex){
			ex.printStackTrace();
		}
	}

	@Override
	public void areaSelected(AreaSelectorEvent event) {
		getUI().addImageAsDrawing(event.getImage());
		finish();
	}

	@Override
	public void selectionCanceled(AreaSelectorEvent event) {
		finish();
	}

	private void finish() {
		getUI().showUI();
		areaSelector.removeListener(this);
		areaSelector.setVisible(false);
		areaSelector = null;
	}

}
